<!-- 文件上传组件 
用法示列
<videoUpload
              :acceptSize="200 * 1024 * 1024"
              :auto-upload="false"
              :file="user.file"
              :show-file-list="true"
              dir="video"
              :limit="1"
              @setUrl="setUrl"
              list-type="picture-card"
              ref="fileRef"
            >
            </fileUpload>
  当模态框显示后，需要显示调用init()方法，示列如下：
  this.dialogDetailBox=true;
  this.$nextTick(() => {
    this.$refs.fileRef.init();
  });
-->
<template>
  <div>
    <el-upload
      :action="action"
      :auto-upload="autoUpload"
      :before-upload="beforeUpload"
      :data="fileOtherData"
      :file-list="fileList"
      :limit="limit"
      :multiple="multiple"
      :on-change="handleChange"
      :on-error="handleError"
      :on-success="handleSuccess"
      :on-exceed="handleExceed"
      :on-remove="handleRemove"
      :ref="uploadRef"
      :show-file-list="showFileList"
      class="avatar-uploader"
      v-bind:on-progress="uploadVideoProcess"
    >
      <video
        v-if="videoFlag"
        v-bind:src="fileUrl"
        class="avatar video-avatar"
        controls="controls"
      >您的浏览器不支持视频播放</video>
      <el-button v-else slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-progress
        v-if="videoPercentFlag"
        type="circle"
        v-bind:percentage="videoUploadPercent"
        style="margin-top:7px;"
      ></el-progress>

      <el-button
        v-if="!videoFlag"
        style="margin-left: 10px;"
        size="small"
        type="success"
        @click.stop="submitUpload"
      >上传到服务器</el-button>
    </el-upload>
  </div>
</template>

<script>
import { get } from "@/utils/request.js";

export default {
  props: {
    uploadRef: {
      type: String,
      default: "videofile"
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: true
    },
    // 是否自动上传
    autoUpload: {
      type: Boolean,
      default: false
    },
    // 是否显示上传列表
    showFileList: {
      type: Boolean,
      default: true
    },
    // 最大允许上传个数
    limit: {
      type: Number,
      default: null
    },
    // 允许上传的文件大小 单位：字节
    acceptSize: {
      type: Number,
      default: 200 * 1024 * 1024
    },
    // 默认额外上传数据
    fileOtherData: {
      type: Object,
      default: function() {
        return {
          key: "",
          policy: "",
          OSSAccessKeyId: "",
          success_action_status: 200,
          signature: ""
        };
      }
    },
    // 文件存储目录
    dir: {
      type: String,
      default: "video"
    },
    fileUrl: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      videoFlag: false,
      videoPercentFlag: false,
      disabled: true,
      // 是否上传失败
      isUploadError: false,
      fileLength: 0,
      action: "",
      waitUpload: [],
      // fileList: [],
      videoUploadPercent: ""
    };
  },
  watch: {
    fileUrl: function(val) {
      if (val) {
        // this.fileList=[{name:val,url:val}];
        this.videoFlag = true;
      } else {
        // this.fileList = [];
        this.videoFlag = false;
      }
      this.videoPercentFlag = false;
    }
  },
  computed: {
    fileList() {
      let fileList = [];
      if (this.fileUrl) {
        fileList = [{ url: this.fileUrl, name: this.fileUrl }];
      }
      return fileList;
    }
  },
  methods: {
    // 附件上传前触发
    async beforeUpload(file) {
      const vm = this;
      var fileSize = file.size > vm.acceptSize;
      if (
        [
          "video/mp4",
          "video/ogg",
          "video/flv",
          "video/avi",
          "video/wmv",
          "video/rmvb",
          "video/mov"
        ].indexOf(file.type) == -1
      ) {
        vm.$message.error("请上传正确的视频格式");
        return false;
      }
      if (fileSize) {
        vm.$message.error("视频大小不能超过50MB");
        return false;
      }
      await get("/file/getPolicyUploadInfo", { dir: vm.dir }).then(res => {
        vm.fileOtherData.key = vm.dir + "/" + new Date().getTime() + file.name;
        vm.fileOtherData.policy = res.data.data.policy;
        vm.fileOtherData.OSSAccessKeyId = res.data.data.accessid;
        vm.fileOtherData.signature = res.data.data.signature;
        vm.action = res.data.data.host;
      });
    },
    //进度条
    uploadVideoProcess(event, file, fileList) {
      this.videoFlag = false;
      this.videoPercentFlag = true;
      this.videoUploadPercent = file.percentage.toFixed(0) * 1;
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handleChange(file, fileList) {
      const vm = this;
      console.log(file);
      if (file.status == "ready") {
        vm.waitUpload.push({ uid: file.uid });
      }
      if ("success" === file.status) {
        console.log("handleChange success", vm.file);
        console.log("handleChange success", fileList);
      }
    },
    renderSize(value) {
      if (null == value || value == "") {
        return "0 B";
      }
      const unitArr = new Array(
        "B",
        "KB",
        "MB",
        "GB",
        "TB",
        "PB",
        "EB",
        "ZB",
        "YB"
      );
      let index = 0;
      let srcsize = parseFloat(value);
      index = Math.floor(Math.log(srcsize) / Math.log(1024));
      let size = srcsize / Math.pow(1024, index);
      size = size.toFixed(2);
      if (unitArr[index]) {
        return size + unitArr[index];
      }
      return "文件太大";
    },
    handleSuccess(response, file, fileList) {
      let vm = this;
      this.videoFlag = true;
      this.videoPercentFlag = false;
      this.videoUploadPercent = 0;
      let fileUrl = vm.action + "/" + vm.fileOtherData.key;
      vm.waitUpload.forEach((item, index) => {
        if (item.uid === file.uid) {
          vm.waitUpload.splice(index, 1);
        }
      });
      vm.$message.success("上传成功");
      vm.$emit("update:fileUrl", fileUrl);
    },
    // 附件上传失败
    handleError() {
      const vm = this;
      vm.$message.error("上传失败，请重试");
      vm.isUploadError = true;
    },
    // 删除附件回调
    handleRemove(file, fileList) {
      const vm = this;
      vm.waitUpload.forEach((item, index) => {
        if (file.uid && item.uid === file.uid) {
          vm.waitUpload.splice(index, 1);
        }
      });

      this.$emit("update:fileUrl", null);
      return true;
    },
    // 文件超出个数限制时的钩子
    handleExceed() {
      const vm = this;
      vm.$message("当前最多允许上传" + vm.limit + "个文件");
    },
    // 附件上传服务器触发方法
    async submitUpload() {
      const vm = this;
      if (vm.waitUpload.length < 1) {
        vm.$message("请先选择文件！");
        return;
      }
      await vm.$refs[vm.uploadRef].submit();
    }
  }
};
</script>
<style scoped>
.avatar {
  width: 100%;
  height: 100%;
}
.el-form-item__content {
  line-height: 0;
}
.el-upload-list--picture-card .el-upload-list__item {
  margin: 0 8px 0 0;
}
.el-upload--picture-card,
.el-upload-list--picture-card .el-upload-list__item {
  width: 128px;
  height: 128px;
}
.limit .el-upload--picture-card {
  display: none;
}
</style>
